#include	"storage.h"
#include	<memory>

Storage & Storage::Get() {
	static std::unique_ptr<Storage> GStorage;
	if (!GStorage) GStorage.reset(new Storage);
	return *(GStorage.get());
}

std::string Storage::Get(const std::string & sKey) {
	auto it = _mCache.find(sKey);
	if (it == _mCache.end()) return "";

	time_t nCur = time(NULL);
	if (nCur >= it->second.nExpire) {
		_mCache.erase(it);
		return "";
	} else {
		if (it->second.nExpire != INT32_MAX) it->second.nExpire = nCur + _nExpire;
		return it->second.sValue;
	}
}

void Storage::Set(const std::string & sKey, const std::string & sValue, bool bNeverExpire) {
	if (sValue.empty()) {
		_mCache.erase(sKey);
	} else {
		StorageData iData;
		iData.sValue = sValue;
		iData.nExpire = bNeverExpire ? INT32_MAX : _nExpire + time(NULL);
		_mCache[sKey] = iData;
	}
}
